<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>取消请求</title>
        <script src="https://cdn.bootcdn.net/ajax/libs/axios/0.21.1/axios.min.js"></script>
    </head>
    <body>
        <button>发送请求</button>
        <button>取消请求</button>
        <script>
            // xhr.abort();
            //获取按钮
            let btns = document.querySelectorAll('button');
            //1. 声明外部变量
            let cancel;

            //绑定事件
            btns[0].onclick = async function(){
                let result = await axios.get('http://127.0.0.1:8090/delay-server', {
                    // 2. 设置 cancelToken 属性
                    cancelToken: new axios.CancelToken(c => {
                        cancel = c;
                    })
                });
                console.log(result);
            }

            //绑定事件 取消请求
            btns[1].onclick = function(){
                //3. 执行cancel函数
                if(cancel) cancel();
            }

        </script>
    </body>
</html>
